using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Domain.Context;
using Domain.Logging;
using WebUI.Infrastructure;

namespace WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private LogService _logger;

        public MvcApplication()
        {
            this.Error += MvcApplication_Error;
            this._controllerFactory = new NinjectControllerFactory();
            var controllerFactory = (_controllerFactory as NinjectControllerFactory);
            _logger = controllerFactory.getLogger(null);
        }

        void MvcApplication_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            if (exception is HttpException)
            {
                if (exception.Message.Contains("NoCatch") || exception.Message.Contains("maxUrlLength"))
                    return;

                Server.Transfer("HttpErrorPage.aspx");
            }
            else
            {
                _logger.WriteError(exception.ToString());

                Response.Clear();
                Response.Redirect("DatabaseError", false);

                Server.ClearError();
            }
        }


        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");

            routes.MapRoute(
                String.Empty,
                String.Empty,
                new { controller = "NMCTerritory", action = "Index" }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        private IControllerFactory _controllerFactory;
        
        protected void Application_Start()
        {
            _logger.WriteMessage("NMC Tool web application starting");

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
			
			ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder();
            ControllerBuilder.Current.SetControllerFactory(_controllerFactory);
        
        }

    }
}